package kr.ltkblue;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class UrlConn {
	public static void main(String[] args) throws Exception {
		UrlConn urlConn = new UrlConn();
		urlConn.insertData("경남","경상남도",true);
	}

	public void insertData(String si,String sido,Boolean emptyTable) throws Exception{
		si=URLEncoder.encode(si);
		sido = URLEncoder.encode(sido);
		String linesep ="\r\n";
		Map keyMap = new HashMap();
		keyMap.put("['sigungu_name']", "sigungu_name");
		keyMap.put("tel", "tel");
		keyMap.put("name", "name");
		keyMap.put("['address_new']", "address_new");
		keyMap.put("address", "address");
		keyMap.put("['map_x']", "map_x");
		keyMap.put("['map_y']", "map_y");
		keyMap.put("['location_info']", "location_info");

		List list = new ArrayList();
		JsonArray jsonArray = new JsonArray();
		boolean breakFlag=false;
		for (int j = 1; j <= 9999; j++) {
			HttpURLConnection httpConn = null;
			String urlParameters = "callCount=1"+linesep
									+"page=/htmlparse/NH/"+linesep
									+"httpSessionId="+linesep
									+"scriptSessionId=0DC6A796024EC48F29A2731981955DE1461"+linesep
									+"c0-scriptName=AspNonghyupNewDAO"+linesep
									+"c0-methodName=getList"+linesep
									+"c0-id=0"+linesep
									+"c0-e1=string:1"+linesep
									+"c0-e2=string:"+si+linesep
									+"c0-e3=string:"+sido+linesep
									+"c0-e4=string:"+linesep
									+"c0-e5=string:3"+linesep
									+"c0-e6=string:map"+linesep
									+"c0-e7=string:"+j+""+linesep
									+"c0-e8=string:0"+linesep
									+"c0-e9=string:"+linesep
									+"c0-e10=string:"+linesep
									+"c0-e11=string:"+linesep
									+"c0-e12=string:"+linesep
									+"c0-e13=string:"+linesep
									+"c0-e14=string:"+linesep
									+"c0-e15=string:"+linesep
									+"c0-e16=string:1"+linesep
									+"c0-e17=string:"+linesep
									+"c0-e18=string:1"+linesep
									+"c0-e19=string:"+linesep
									+"c0-e20=string:1"+linesep
									+"c0-e21=string:"+linesep
									+"c0-e22=string:"+linesep
									+"c0-e23=string:"+linesep
									+"c0-param0=Object_Object:{menu:reference:c0-e1, sido:reference:c0-e2, full_sido:reference:c0-e3, sigungu:reference:c0-e4, search_type:reference:c0-e5, map_type:reference:c0-e6, pg:reference:c0-e7, scroll_top:reference:c0-e8, list_tab:reference:c0-e9, seq_no:reference:c0-e10, s_menu:reference:c0-e11, region:reference:c0-e12, region_name:reference:c0-e13, oil_poll:reference:c0-e14, oil_name:reference:c0-e15, nh_type:reference:c0-e16, atm_type:reference:c0-e17, search_cond:reference:c0-e18, search_word:reference:c0-e19, chk_addr:reference:c0-e20, search_sido:reference:c0-e21, search_sigungu:reference:c0-e22, search_addr:reference:c0-e23}"+linesep
									+"batchId=0";
			String targetURL = "http://nonghyup.chzero.com/dwr/call/plaincall/AspNonghyupNewDAO.getList";
	//		String targetURL = "http://www.ltkblue.co.kr:88/htmlparse/NH/";
			URL url = new URL(targetURL);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
			// httpConn.setRequestProperty("Cookie", "cookievalue="+ cookie);
	//
			httpConn.setUseCaches(false);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);

			PrintWriter pw = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(), "utf-8"));
			pw.write(urlParameters);
			pw.flush();
			pw.close();

			// Get Response
			BufferedReader rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			String line;

			StringBuffer sb = new StringBuffer();
			while ((line = rd.readLine()) != null) {
	//			System.out.println(line);
				sb.append(line);
				// response1.append('\r');
			}

			httpConn.disconnect();
			rd.close();

			String[] param = sb.toString().split(";");
			Map map = new HashMap();
			JsonObject job = new JsonObject();

			for (int i = 0; i < param.length; i++) {
				String data[] = param[i].split("=");
				if(data.length>1){

//					System.out.println(data[0]+"   =   "+decode(data[1].replaceAll("\"", "").trim()));
					Set<String> keySet = keyMap.keySet();
					Iterator<String> iterator = keySet.iterator();
					while (iterator.hasNext()) {
						String key = iterator.next();
						Object value = keyMap.get(key);
						if(data[0].indexOf(key)>0){
							map.put(value, decode(data[1].replaceAll("\"", "").trim()));
							job.addProperty(value.toString(), decode(data[1].replaceAll("\"", "").trim()));
							if(value.equals("location_info")){
								list.add(map);
								jsonArray.add(job);
								map = new HashMap();
								job = new JsonObject();
//								System.out.println(list.size());
							}

						}
					}
				}
				if(data[0].indexOf(".cnt")>0){
					if(Integer.parseInt(data[1])<=list.size()){
						breakFlag=true;
						break;
					}
				}
			}
			if(breakFlag)break;
		}
//
//		for (int i = 0; i < list.size(); i++) {
//			Map item = (Map) list.get(i);
//			Set<String> keySet = item.keySet();
//			Iterator<String> iterator = keySet.iterator();
//			while (iterator.hasNext()) {
//				String key = iterator.next();
//				Object value = item.get(key);
////				System.out.println("no"+i+".  "+key +"  ="+value);
//			}
//
//		}

		ObjectMapper om = new ObjectMapper();
		// Map or List Object �� JSON ���ڿ��� ��ȯ
		String jsonStr = om.writeValueAsString(list);
//		System.out.println(jsonStr);

		JsonObject jsonObject = new JsonObject();
		jsonObject.add("data", jsonArray);
		jsonObject.addProperty("emptyTable", emptyTable);
		System.out.println(jsonObject.toString());

		SendJsonData sendJsonData = new SendJsonData();
		sendJsonData.sendJson(jsonObject.toString());
	}

	public static String unicodeToString(String str){

		String uniCodeStr = String.format(str);
		String[] rawUnicode = uniCodeStr.split("\\");
		StringBuffer sb = new StringBuffer();
		int intVal = 0;
		char[] chVal;

		for(int i = 0; i < rawUnicode.length; i++ ) {
			chVal = rawUnicode[i].toCharArray();
			for(int j = 0; j < chVal.length; j++ ) {
				intVal = chVal[j];
				sb.append(chVal[j]);
			}
		}

		return sb.toString();
	}


	 public static String decode(String unicode)throws Exception {
	  StringBuffer str = new StringBuffer();

	  char ch = 0;
	  for( int i= unicode.indexOf("\\u"); i > -1; i = unicode.indexOf("\\u") ){
	   ch = (char)Integer.parseInt( unicode.substring( i + 2, i + 6 ) ,16);
	   str.append( unicode.substring(0, i) );
	   str.append( String.valueOf(ch) );
	   unicode = unicode.substring(i + 6);
	  }
	  str.append( unicode );

	  return str.toString();
	 }

}
